﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using WcfMasterSlaveElectionService;

namespace MasterSlaveConsole
{
    public class EndpointProvider : IEndpointProvider
    {
        string _id;
        private const string ElectionServiceEndpointName = "MasterElectionService";
        Dictionary<string, string> _electionServices = null;
        Dictionary<string, InstanceEndpoint> _endpoints = null;

        public EndpointProvider(string id)
        {
            _id = id;
        }

        public Dictionary<string, string> GetCurrentEndpoints()
        {
            string port;
            string otherId;
            string otherPort;

            if (_id == "1")
            {
                port = "20001";
                otherId = "2";
                otherPort = "20002";
            }
            else
            {
                port = "20002";
                otherId = "1";
                otherPort = "20001";
            }

           

            if (_electionServices == null)
            {
                _electionServices = new Dictionary<string, string>();
                var uri = String.Format("net.tcp://127.0.0.1:{0}/MasterElectionService", otherPort);
                _electionServices.Add(otherId, uri);

                uri = String.Format("net.tcp://127.0.0.1:{0}/MasterElectionService", port);
                _electionServices.Add(_id, uri);
            }


            if (_endpoints == null)
            {
                _endpoints = new Dictionary<string, InstanceEndpoint>();
                Console.WriteLine("Filling list of endpoints");

                InstanceEndpoint endpoint = new InstanceEndpoint();
                endpoint.Id = _id;
                endpoint.Uri = String.Format("net.tcp://127.0.0.1:{0}/MasterElectionService", port);
                _endpoints.Add(_id, endpoint);
                Console.WriteLine("Added " + endpoint.Id + " with url " + endpoint.Uri);

                endpoint = new InstanceEndpoint();
                endpoint.Id = otherId;
                endpoint.Uri = String.Format("net.tcp://127.0.0.1:{0}/MasterElectionService", otherPort);
                _endpoints.Add(otherId, endpoint);
                Console.WriteLine("Added " + endpoint.Id + " with url " + endpoint.Uri);
            }

            return _electionServices;
        }

        public InstanceEndpoint GetEndPointOfRoleIntance(string roleInstanceId)
        {
            return _endpoints[roleInstanceId];
        }

        public string GetUriForRoleIntance(string roleInstanceId)
        {
            return _endpoints[roleInstanceId].Uri;
        }

        public string EndpointName
        {
            get { return ElectionServiceEndpointName; }
        }

        public string RoleName
        {
            get { return _id; }
        }

    }
}
